package com.zhf.testDBUtils;

/**
 * @Author: ZhaoHuanfeng
 * @Date: 2020/9/24 22:30
 */

import com.zhf.utils.DruidUtils;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.junit.Test;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 使用QueryRunner对象完成增删改
 *  update(Connection con,String sql,Object... param)
 */
public class DBUtilsDemo02 {

    //插入操作
    @Test
    public void testInsert() throws SQLException {
        //创建QueryRunner手动模式创建
        QueryRunner queryRunner=new QueryRunner();

        //编写占位符方式SQL
        String sql="insert into employee values(?,?,?,?,?,?)";

        //设置占位符的参数
        Object[] param={null,"张三",20,"女",1000,"1997-12-13"};

        //执行update方法
        Connection connection = DruidUtils.getConnection();
        int i = queryRunner.update(connection, sql, param);

        //释放资源
        DbUtils.closeQuietly(connection);
    }

    //修改操作
    @Test
    public void testUpdat() throws SQLException {
        //自动模式创建 传入数据库连接池对象
        QueryRunner queryRunner=new QueryRunner(DruidUtils.getDataSource());

        //编写sql
        String sql="update employee set salary=? where ename=?";

        //设置占位符参数
        Object[] param={15000,"张三"};

        //执行SQL 自动模式无需传入connection对象
        queryRunner.update(sql,param);
    }

    //删除操作
    @Test
    public void testDelete() throws SQLException {
        QueryRunner queryRunner=new QueryRunner(DruidUtils.getDataSource());

        String sql="delete from employee where eid=?";

        //如果只有一个参数则无需创建数组
        //执行sql
        queryRunner.update(sql,1);
    }
}
